/*
 * Copyright 2011-2012 by The Regents of the University of California Licensed
 * under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. you may obtain a copy of the
 * License from
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package edu.ucsd.db.bassarisk.scoring;

import edu.ucsd.db.bassarisk.exception.VisitorException;
import edu.ucsd.db.bassarisk.query.Constants;
import edu.ucsd.db.bassarisk.query.binding.BindingFactory;
import edu.ucsd.db.bassarisk.query.binding.Bindings.Binding;
import edu.ucsd.db.bassarisk.query.binding.Bindings.PositionBinding;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.EstablishingNode;
import edu.ucsd.db.bassarisk.query.path.DSDElements.DSDFilter;

public class AllTokensScoringSignalBranchBuilder extends
    SimpleScoringSignalBranchBuilder {
  private final PositionBinding tokenMatchBinding;

  public AllTokensScoringSignalBranchBuilder(final BindingFactory bindingFactory,
                                             final PositionBinding tokenMatchBinding) {
    super(bindingFactory);
    this.tokenMatchBinding = tokenMatchBinding;
  }

  @Override
  public Binding visitFilter(final DSDFilter elem, final EstablishingNode parent)
      throws VisitorException {
    assert elem.getFilterValue().equals(Constants.AllTokens);
    PositionBinding filterBinding = (PositionBinding) parent.getEstablishedBinding();
    filterBinding.setFilter(this.tokenMatchBinding.getValueFilter());
    if (elem.hasNext()) {
      // The aggregated values must be a position space attribute identified by
      // the next node.
      return elem.getNext().accept(this, parent);
    } else {
      // The aggregated values must be the filter attached to the grandparent
      // establishing node.
      return filterBinding;
    }
  }
}
